package com.song.shop.dynamic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Song Yinghui
 * @date 2018/8/23
 * @Version 1.0
 *
 *
 * 使用ThreadLocal 来保证线程安全
 *
 */
public class DynamicDataSourceHolder {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceHolder.class);
    public static final String MASTER = "master" ;  //主库

    private static final String SLAVE = "slave" ;

    private static final ThreadLocal<String> holder = new ThreadLocal<String>();


    public static void setDataSource(String key ){
        logger.info("更换数据源，当前数据源为 [{}]" , key);
        holder.set(key);
    }


    public static String getDataSource(){
        return holder.get();
    }

    public static void clear(){
        holder.remove();
    }


    /**
     *  标记 是主库
     */
    public static void markMaster(){
        setDataSource(MASTER);
    }

    public static void markSlave(){
        setDataSource(SLAVE);
    }
}
